const app = getApp()
const util = require('../../../../../../utils/util.js');
const time = require('../../../../../../utils/time.js');
const api = require('../../../../../../config/api.js');
Page({
  data: {
    groupDataInfo: {},// 初始化加载的数据库数据
    //辅助数据  step步骤  nowDate当前的时间  showOccupied不可选日期弹窗控制  addTheme判断是添加主题还是新建主题组
    auxiliary: { "step": 0, "nowDate": util.getDateStr(new Date(), 0), "showOccupied": false, "addTheme": 0, "circleid": "", "groupid": "", "screenInfoSelectIndex": "" },
    //选中的主题
    groupInfo: { "groupName": "", "selectTheme": [], "sortType": 1, "screenInfo": {}, "placeDate": "" },
    // 不能选择的日期
    themeNotSelectTime: []
  },
  onLoad: function (options) {
    var _this = this;
    var addTheme = options.addTheme == null ? 0 : options.addTheme;
    var circleid = options.circleid == null ? "" : options.circleid;
    var groupid = options.groupid == null ? "" : options.groupid;
    _this.setData({
      ["auxiliary.addTheme"]: addTheme,
      ["auxiliary.circleid"]: circleid,
      ["auxiliary.groupid"]: groupid,
    })
    wx.setNavigationBarTitle({
      title: addTheme == 1 ? "添加主题" : "创建主题组",
    })
    _this.getThemeByGroupThatTime();
    _this.getThemeNotSelectTime();
  },
  /**
   * 查询不可选的日期（只过滤主题、以及主题中已有关联主题组的）
   */
  getThemeNotSelectTime: function () {
    var _this = this;
    var openid = app.globalData.logininfo.openid;
    if (openid != null && openid != "") {
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        var data = {};
        data.openid = openid;
        data.circleid = _this.data.auxiliary.circleid;
        data.access_token = res.access_token;
        util.post(api.Interest_GetThemeNotSelectTimeApi, data).then(function (res) {
          if (res.code == 200) {
            _this.setData({
              themeNotSelectTime: res.result
            })
          }
        })
      })
    }
  },
  /**
   * 获取分组时的主题信息
   */
  getThemeByGroupThatTime: function () {
    var _this = this;
    var openid = app.globalData.logininfo.openid;
    if (openid != null && openid != "") {
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        var data = {};
        data.openid = openid;
        data.groupid = _this.data.auxiliary.groupid;
        data.circleid = _this.data.auxiliary.circleid;
        data.access_token = res.access_token;
        util.post(api.Interest_GetThemeByGroupThatTimeApi, data).then(function (res) {
          if (res.code == 200) {
            _this.setData({
              groupDataInfo: res.result
            })
          }
        })
      })
    }
  },
  /**
   * 选择步骤
   */
  selectStep: function (e) {
    var _this = this;
    var index = e.currentTarget.dataset.index;
    var step = _this.data.auxiliary.step;
    if (index < step) {
      _this.setData({
        ["auxiliary.step"]: index
      })
    }
  },
  /**
   * 选中主题
   */
  selectTheme: function (e) {
    var _this = this;
    var index = e.currentTarget.dataset.index;
    var selectTheme = _this.data.groupInfo.selectTheme;
    var theme = _this.data.groupDataInfo.themeList[index];
    var selectThemeIndex = -1;
    for (var j = 0; j < selectTheme.length; j++) {
      if (theme.themeid == selectTheme[j].themeid) {
        selectThemeIndex = j;
        break;
      }
    }
    if (selectThemeIndex > -1) {
      // 已选中，需要取消
      selectTheme.splice(selectThemeIndex, 1);
      _this.setData({
        ["groupDataInfo.themeList[" + index + "].checked"]: false
      })
    } else {
      // 未选中，需要选中
      selectTheme.push(theme);
      _this.setData({
        ["groupDataInfo.themeList[" + index + "].checked"]: true
      })
    }
    _this.setData({
      ["groupInfo.selectTheme"]: selectTheme
    })
  },
  /**
   * 下一步
   */
  nextStep: function () {
    var _this = this;
    var addTheme = _this.data.auxiliary.addTheme;
    if (addTheme == 1) {
      // 添加主题到组里面
      _this.addThemeToGroup();
    } else {
      var step = _this.data.auxiliary.step;
      if (step == 0) {
        _this.jsOrderTheme();
      }
      _this.setData({
        ["auxiliary.step"]: parseInt(step + 1)
      })
    }
  },

  /**
   * 添加主题到组里面
   */
  addThemeToGroup: function(){
    var _this = this;
    var circleid = _this.data.auxiliary.circleid;
    var groupid = _this.data.auxiliary.groupid;
    var openid = app.globalData.logininfo.openid;
    var selectThemeList = _this.data.groupInfo.selectTheme;
    if (openid != null && openid != "") {
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        var data = {};
        data.openid = openid;
        data.access_token = res.access_token;
        data.circleid = circleid;
        data.groupid = groupid;
        data.selectThemeList = selectThemeList;
        util.post(api.Interest_AddThemeToGroupApi, data).then(function (res) {
          if (res.code == 200) {
            wx.navigateBack({
              delta: 1
            });
          }
        })
      })
    }
  },

  /**
   * 计算排序主题或主题组
   */
  jsOrderTheme: function () {
    var _this = this;
    var sortType = _this.data.groupInfo.sortType;
    var screenInfoList = _this.data.groupDataInfo.screenInfoList;
    var themeType = _this.data.groupDataInfo.themeType;
    var screenInfoList2 = [];
    var selectTheme = _this.data.groupInfo.selectTheme;
    for (var i = 0; i < screenInfoList.length; i++) {
      var isAdd = true;
      var type = screenInfoList[i].type;
      var dataid = screenInfoList[i].dataid;
      var groupid = screenInfoList[i].groupid;
      if (type == 1) {
        for (var j = 0; j < selectTheme.length; j++) {
          var themeid = selectTheme[j].themeid;
          if (dataid == themeid) {
            isAdd = false;
          }
        }
        if (themeType == 1 && sortType == 1) {
          // 需要过滤主题组、已经有关联组的主题
          if (groupid != null && groupid > 0) {
            isAdd = false;
          }
        }
      }
      if (themeType == 1 && sortType == 2) {
        // 经典模式，排在谁后面
        // 需要过滤前后只相隔一天的主题、或者主题组
        var time1 = screenInfoList[i].time;
        if (i > 0 && i < screenInfoList.length - 1){
          var time2 = screenInfoList[i + 1].time;
          var day = time.calculateDifferDay(time1, time2);
          if(day <= 1){
            isAdd = false;
          }
        }
      }
      if (isAdd) {
        screenInfoList2.push(screenInfoList[i]);
      }
    }
    _this.setData({
      ["groupDataInfo.screenInfoList2"]: screenInfoList2,
    })
    if (screenInfoList2.length > 0) {
      _this.setData({
        ["groupInfo.screenInfo"]: screenInfoList2[0],
        ["auxiliary.screenInfoSelectIndex"]: 0
      })
    } else {
      _this.setData({
        ["groupInfo.screenInfo"]: {},
        ["auxiliary.screenInfoSelectIndex"]: ""
      })
    }
  },

  /**
   * 设置组名
   */
  inputGroupName: function (e) {
    var _this = this
    var value = e.detail.value.replace(/\s+/g, '')
    _this.setData({
      ["groupInfo.groupName"]: value,
    })
  },
  /**
   * 选择排位类型
   */
  selectSortType: function (e) {
    var _this = this;
    var sortType = _this.data.groupInfo.sortType;
    var index = e.currentTarget.dataset.index;
    _this.setData({
      ["groupInfo.sortType"]: index
    })
    if (sortType != index){
      _this.jsOrderTheme();
    }
  },
  /**
   * 选中排位的目标
   */
  selectScreenInfo: function (e) {
    var _this = this
    var index = e.detail.value;
    var screenInfoList2 = _this.data.groupDataInfo.screenInfoList2;
    _this.setData({
      ["groupInfo.screenInfo"]: screenInfoList2[index]
    })
    var sortType = _this.data.groupInfo.sortType;
    if (sortType == 2){
      // 排在谁后面
      // 因为是排在后面，所有index要加1，
      // 因为.length，是不会有0的，所以-1
      if (index + 2 > screenInfoList2.length - 1){
        // 后面没有内容，会变为独立组
        util.showToast("当前主题组将会成为独立组，放在你所选择的主题后面排序","none");
      }else{
        // 后面有内容
        if (screenInfoList2[index + 1].type == 2){
          // 后面内容是组，会变为独立组
          util.showToast("当前主题组将会成为独立组，放在你所选择的主题后面排序", "none");
        }else{
          util.showToast("当前主题组将会与你选择的主题后面的主题同时显示", "none");
        }
      }
    }
  },
  /**
   * 选中排位的时间
   */
  selectPlaceDate: function (e) {
    var _this = this
    var date = e.detail.value;
    var themeNotSelectTime = _this.data.themeNotSelectTime;
    for (var i = 0; i < themeNotSelectTime.length; i++) {
      if (themeNotSelectTime[i] == date) {
        util.showToast("不能选择" + date, "none");
        return;
      }
    }
    _this.setData({
      ["groupInfo.placeDate"]: date
    })
  },
  /**
   * 打开已选日期面板
   */
  openOccupied: function () {
    var _this = this;
    _this.setData({
      ["auxiliary.showOccupied"]: true
    })
  },
  /**
   * 关闭所有弹窗
   */
  closeMC: function () {
    var _this = this;
    _this.setData({
      ["auxiliary.showOccupied"]: false,
    })
  },
  /**
   * 添加组题组
   */
  saveThemeGroup: function(){
    var _this = this;
    var circleid = _this.data.auxiliary.circleid;
    var openid = app.globalData.logininfo.openid;
    var groupName = _this.data.groupInfo.groupName;
    var selectThemeList = _this.data.groupInfo.selectTheme;
    var sortType = _this.data.groupInfo.sortType;
    var screenInfo = _this.data.groupInfo.screenInfo;
    var placeDate = _this.data.groupInfo.placeDate;
    if (openid != null && openid != "") {
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        var data = {};
        data.openid = openid;
        data.access_token = res.access_token;
        data.circleid = circleid;
        data.groupName = groupName;
        data.selectThemeList = selectThemeList;
        data.sortType = sortType;
        data.screenInfo = screenInfo;
        data.placeDate = placeDate;
        util.post(api.Interest_SaveThemeGroupApi, data).then(function (res) {
          if (res.code == 200) {
            util.showToast("添加成功", "success");
            setTimeout(function () {
              wx.navigateBack({
                delta: 1
              });
            }, 1000)
          }
        })
      })
    }
  }
})